<template>
    <div class="sales-create-page">
        <el-container>
            <el-main class="page-body">
                <el-form ref="salesFormRef" :model="salesForm" :rules="rules" label-width="120px" class="sales-form">
                    <el-card class="card-block">
                        <template #header>
                            <span class="card-title">基础信息</span>
                        </template>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="销售单号" prop="salesOrderNo">
                                    <el-input
                                        v-model="salesForm.salesOrderNo"
                                        placeholder="自动获取系统编号"
                                        readonly
                                        class="readonly-input"
                                    >
                                        <template #append>
                                            <el-button @click="generateSalesOrderNo" :loading="generatingCode">
                                                自动生成
                                            </el-button>
                                        </template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="销售日期" prop="salesOrderDate">
                                    <el-date-picker
                                        v-model="salesForm.salesOrderDate"
                                        type="date"
                                        value-format="YYYY-MM-DD"
                                        placeholder="请选择"
                                        style="width: 100%"
                                    />
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="客户名称" prop="customerId">
                                    <div class="inline-input">
                                        <el-select
                                            v-model="salesForm.customerId"
                                            placeholder="请选择"
                                            filterable
                                            clearable
                                            style="flex: 1"
                                            @change="handleCustomerChange"
                                        >
                                            <el-option
                                                v-for="item in customerOptions"
                                                :key="item.customerId"
                                                :label="item.customerName"
                                                :value="String(item.customerId)"
                                            />
                                        </el-select>
                                        <el-button type="text" class="link-btn" @click="gotoCreateCustomer">
                                            设置
                                        </el-button>
                                    </div>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="联系人">
                                    <el-input v-model="salesForm.salesContact" placeholder="请输入" />
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="联系方式">
                                    <el-input v-model="salesForm.salesContactPhone" placeholder="请输入" />
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="销售部门" prop="organizationId">
                                    <el-input
                                        v-model="salesForm.organizationName"
                                        placeholder="请选择"
                                        readonly
                                        @click="openOrgDialog"
                                    >
                                        <template #suffix>
                                            <el-button v-if="salesForm.organizationId" text @click.stop="clearOrgSelection">
                                                <el-icon><Close /></el-icon>
                                            </el-button>
                                            <el-button text @click.stop="openOrgDialog">···</el-button>
                                        </template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="销售负责人" prop="userId">
                                    <el-input
                                        v-model="salesForm.userName"
                                        placeholder="请选择"
                                        readonly
                                        @click="openUserDialog"
                                    >
                                        <template #suffix>
                                            <el-button v-if="salesForm.userId" text @click.stop="clearUserSelection">
                                                <el-icon><Close /></el-icon>
                                            </el-button>
                                            <el-button text @click.stop="openUserDialog">···</el-button>
                                        </template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="备注">
                                    <el-input v-model="salesForm.remark" type="textarea" :rows="3" placeholder="请输入" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-card>

                    <el-card class="card-block">
                        <template #header>
                            <div class="detail-header">
                                <span class="card-title">销售货品明细</span>
                                <div class="detail-actions">
                                    <el-button type="primary" @click="openProductDialog">新增</el-button>
                                    <el-button
                                        type="danger"
                                        plain
                                        :disabled="!selectedDetailRows.length"
                                        @click="removeSelectedDetails"
                                    >
                                        移除
                                    </el-button>
                                </div>
                            </div>
                        </template>
                        <el-table
                            ref="detailTableRef"
                            :data="salesDetails"
                            border
                            highlight-current-row
                            style="width: 100%"
                            empty-text="请先通过“新增”按钮选择货品"
                            @selection-change="handleDetailSelectionChange"
                        >
                            <el-table-column type="selection" width="50" />
                            <el-table-column type="index" label="序号" width="60" />
                            <el-table-column prop="productName" label="货品名称" min-width="160" show-overflow-tooltip />
                            <el-table-column prop="productCode" label="货品编号" min-width="140" show-overflow-tooltip />
                            <el-table-column label="规格型号" min-width="160" show-overflow-tooltip>
                                <template #default="{ row }">
                                    <el-select
                                        v-model="row.specificationModel"
                                        placeholder="请选择"
                                        clearable
                                        filterable
                                        style="width: 140px"
                                        @change="handleSpecificationChange(row)"
                                    >
                                        <template v-if="row.unitGroups?.length">
                                            <template v-for="group in row.unitGroups" :key="group.label">
                                                <el-option-group :label="group.label">
                                                    <el-option
                                                        v-for="option in group.options"
                                                        :key="option.value"
                                                        :label="option.label"
                                                        :value="option.value"
                                                    />
                                                </el-option-group>
                                            </template>
                                        </template>
                                        <template v-else>
                                            <el-option
                                                v-for="unit in DEFAULT_UNIT_OPTIONS"
                                                :key="unit"
                                                :label="unit"
                                                :value="unit"
                                            />
                                        </template>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="单位" min-width="120">
                                <template #default="{ row }">
                                    {{ row.unitName || '--' }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="productTypeName" label="货品类型" min-width="120" show-overflow-tooltip />
                            <el-table-column prop="currentStock" label="当前库存" width="100" />
                            <el-table-column label="* 货品数量" width="130">
                                <template #default="{ row }">
                                    <el-input-number
                                        v-model="row.quantity"
                                        :min="1"
                                        :precision="0"
                                        controls-position="right"
                                        placeholder="必填"
                                        :value-on-clear="1"
                                        @change="updateDetailAmount(row)"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="* 销售单价" width="130">
                                <template #default="{ row }">
                                    <el-input-number
                                        v-model="row.unitPrice"
                                        :min="0"
                                        :precision="2"
                                        controls-position="right"
                                        placeholder="必填"
                                        :value-on-clear="0"
                                        @change="updateDetailAmount(row)"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="销售金额" width="120">
                                <template #default="{ row }">
                                    ¥{{ (row.amount || 0).toFixed(2) }}
                                </template>
                            </el-table-column>
                            <el-table-column label="备注" min-width="140">
                                <template #default="{ row }">
                                    <el-input v-model="row.remark" placeholder="请输入" />
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="80" fixed="right">
                                <template #default="scope">
                                    <el-button link type="danger" size="small" @click="removeDetail(scope.$index)">移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                        <div class="detail-summary" v-if="salesDetails.length">
                            <span>货品种类：{{ totalProductKinds }}</span>
                            <span>货品数量：{{ totalProductQuantity }}</span>
                            <span>销售金额：¥{{ totalProductAmount.toFixed(2) }}</span>
                        </div>
                    </el-card>
                </el-form>
            </el-main>
        </el-container>

        <div class="fixed-footer">
            <div class="footer-content">
                <el-button @click="goBack">关闭</el-button>
                <el-button @click="resetForm">重置</el-button>
                <el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
            </div>
        </div>

        <!-- 部门对话框 -->
        <el-dialog v-model="orgDialogVisible" title="选择部门" width="520px">
            <el-input
                v-model="orgSearchText"
                placeholder="搜索部门名称"
                clearable
                class="dialog-search"
            />
            <el-tree
                :data="filteredOrgTree"
                node-key="organizationId"
                :props="orgTreeProps"
                highlight-current
                default-expand-all
                :expand-on-click-node="false"
                style="max-height: 360px; overflow: auto"
                @node-click="handleSelectOrg"
            />
            <template #footer>
                <div style="text-align: right">
                    <el-button @click="orgDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmOrg">确定</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 人员对话框 -->
        <el-dialog v-model="userDialogVisible" title="选择销售负责人" width="520px">
            <el-input v-model="userSearchText" placeholder="搜索人员" clearable class="dialog-search" />
            <el-table
                :data="filteredUserList"
                height="360"
                border
                @row-click="handleSelectUser"
                style="cursor: pointer"
            >
                <el-table-column prop="userName" label="姓名" />
                <el-table-column prop="organizationName" label="部门" />
            </el-table>
            <template #footer>
                <div style="text-align: right">
                    <el-button @click="userDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmUser">确定</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 货品选择对话框 -->
        <el-dialog v-model="productDialogVisible" title="选择货品" width="960px">
            <el-form :inline="true" :model="productSearchForm" class="product-search-form">
                <el-form-item>
                    <el-input
                        v-model="productSearchForm.keyword"
                        placeholder="请输入货品编号/名称"
                        clearable
                    />
                </el-form-item>
                <el-form-item>
                    <el-select v-model="productSearchForm.unit" placeholder="请选择单位" clearable filterable>
                        <el-option v-for="unit in productUnitOptions" :key="unit" :label="unit" :value="unit" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="resetProductSearch">重置</el-button>
                    <el-button type="primary" @click="searchProducts">查询</el-button>
                </el-form-item>
            </el-form>

            <el-table
                :data="productList"
                border
                height="420"
                v-loading="productTableLoading"
                @selection-change="handleProductSelectionChange"
            >
                <el-table-column type="selection" width="50" />
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="productCode" label="货品编号" min-width="120" />
                <el-table-column prop="productName" label="货品名称" min-width="140" />
                <el-table-column label="规格型号" min-width="120">
                    <template #default="{ row }">
                        {{ row.productUnit || row.unitDisplay || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="单位" min-width="120">
                    <template #default="{ row }">
                        {{ row.productSpecification || row.specification || '--' }}
                    </template>
                </el-table-column>
                <el-table-column prop="producttypeName" label="货品类型" min-width="120" />
                <el-table-column prop="inventoryCurrtnumber" label="当前库存" min-width="100" />
                <el-table-column prop="productOutMoney" label="销售单价" min-width="120">
                    <template #default="{ row }">
                        ¥{{ formatProductPrice(row) }}
                    </template>
                </el-table-column>
            </el-table>

            <div class="product-pagination">
                <el-pagination
                    v-model:current-page="productPagination.pageindex"
                    v-model:page-size="productPagination.pagesize"
                    :page-sizes="[10, 20, 50]"
                    layout="total, sizes, prev, pager, next"
                    :total="productPagination.total"
                    @size-change="handleProductSizeChange"
                    @current-change="handleProductCurrentChange"
                />
            </div>

            <template #footer>
                <div style="text-align: right">
                    <el-button @click="productDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmProductSelection">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { Close } from '@element-plus/icons-vue'
import { ElMessage, type FormInstance } from 'element-plus'
import myaxios from '@/http/MyAxios'

const router = useRouter()
const salesFormRef = ref<FormInstance>()
const generatingCode = ref(false)
const currentLoginUser = ref(
    (typeof window !== 'undefined' ? localStorage.getItem('username') : '') ||
    (typeof window !== 'undefined' ? localStorage.getItem('userAccount') : '') ||
    '系统'
)

const salesForm = reactive({
    salesOrderNo: '',
    salesOrderDate: '',
    customerId: '',
    customerName: '',
    salesContact: '',
    salesContactPhone: '',
    organizationId: '',
    organizationName: '',
    userId: '',
    userName: '',
    reviewerName: currentLoginUser.value,
    remark: '',
})

const rules = {
    salesOrderNo: [{ required: true, message: '销售单号不能为空', trigger: 'blur' }],
    salesOrderDate: [{ required: true, message: '请选择销售日期', trigger: 'change' }],
    customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
    organizationId: [{ required: true, message: '请选择销售部门', trigger: 'change' }],
    userId: [{ required: true, message: '请选择销售负责人', trigger: 'change' }],
}

interface CustomerItem {
    customerId: string | number
    customerName: string
    linkMan?: string
    linkPhone?: string
}

interface OrganizationItem {
    organizationId: string | number
    organizationName: string
    organizationParentId?: string | number | null
    children?: OrganizationItem[]
}

interface UserItem {
    userId: string | number
    userName: string
    organizationId?: string | number
    organizationName?: string
}

interface UnitItem {
    unitId: string | number
    unitName: string
}

interface UnitOption {
    label: string
    value: string
    description?: string
}

interface UnitOptionGroup {
    label: string
    options: UnitOption[]
}

interface ProductListItem {
    productId: string | number
    productName: string
    productCode: string
    producttypeName?: string
    productUnit?: string
    productSpecification?: string
    specification?: string
    productspecification?: string
    inventoryCurrtnumber?: number
    productInmoney?: number
    productOutMoney?: number
    unitDisplay?: string
    [key: string]: any
}

interface SalesDetailItem {
    lineId: string
    productId: string | number
    productName: string
    productCode: string
    specificationModel?: string
    unitName?: string
    unitId?: string | number | null
    unitGroups?: UnitOptionGroup[]
    productTypeName?: string
    currentStock?: number
    quantity: number | null
    unitPrice: number
    amount: number
    remark: string
}

const DEFAULT_UNIT_OPTIONS = ['箱', '个', '套', '台', '条', '包', '瓶', '袋', '件']

const customerOptions = ref<CustomerItem[]>([])
const unitOptions = ref<UnitItem[]>([])

const orgDialogVisible = ref(false)
const orgTreeData = ref<OrganizationItem[]>([])
const orgTreeProps = { children: 'children', label: 'organizationName' }
const orgSearchText = ref('')
const selectedOrgNode = ref<OrganizationItem | null>(null)

const userDialogVisible = ref(false)
const userList = ref<UserItem[]>([])
const userSearchText = ref('')
const selectedUser = ref<UserItem | null>(null)

const salesDetails = ref<SalesDetailItem[]>([])
const selectedDetailRows = ref<SalesDetailItem[]>([])
const saving = ref(false)

const productDialogVisible = ref(false)
const productTableLoading = ref(false)
const productList = ref<ProductListItem[]>([])
const selectedProducts = ref<ProductListItem[]>([])
const productUnitOptions = ref<string[]>([])

const productSearchForm = reactive({
    keyword: '',
    unit: '',
})

const productPagination = reactive({
    pageindex: 1,
    pagesize: 10,
    total: 0,
})

const PRODUCT_PRICE_FIELDS = [
    'productOutMoney',
    'productoutmoney',
    'productSalePrice',
    'productSaleMoney',
    'salesPrice',
    'salePrice',
    'outPrice',
    'productInmoney',
    'productInMoney',
    'productPrice',
    'price',
    'unitPrice',
]

const normalizePriceValue = (value: any): number | null => {
    if (value === undefined || value === null || value === '') return null
    const num = Number(value)
    if (Number.isNaN(num) || !Number.isFinite(num)) return null
    return num
}

const resolveProductPrice = (product: Record<string, any>): number => {
    for (const key of PRODUCT_PRICE_FIELDS) {
        const price = normalizePriceValue(product?.[key])
        if (price !== null) return price
    }
    return 0
}

const formatProductPrice = (product: Record<string, any>) => {
    return resolveProductPrice(product).toFixed(2)
}

const TIME_SEGMENT_ORDER = ['YYYY', 'YY', 'MM', 'DD', 'HH', 'MI', 'SS']
const pad = (n: number, len = 2) => `${n}`.padStart(len, '0')

const buildCodeFromRule = (rule: any) => {
    const now = new Date()
    const segments = (rule?.timeRule || '')
        .split(',')
        .map((s: string) => s.trim().toUpperCase())
        .filter(Boolean)
        .sort((a: string, b: string) => {
            const idxA = TIME_SEGMENT_ORDER.indexOf(a)
            const idxB = TIME_SEGMENT_ORDER.indexOf(b)
            if (idxA === -1 && idxB === -1) return 0
            if (idxA === -1) return 1
            if (idxB === -1) return -1
            return idxA - idxB
        })
    const timePart = segments
        .map((seg: string) => {
            switch (seg) {
                case 'YYYY': return String(now.getFullYear())
                case 'YY': return String(now.getFullYear()).slice(-2)
                case 'MM': return pad(now.getMonth() + 1)
                case 'DD': return pad(now.getDate())
                case 'HH': return pad(now.getHours())
                case 'MI': return pad(now.getMinutes())
                case 'SS': return pad(now.getSeconds())
                default: return ''
            }
        })
        .join('')
    const serialLength = Number(rule?.serialLength ?? 3)
    const serial = '1'.padStart(serialLength > 0 ? serialLength : 3, '0')
    return `${rule?.codePrefix || ''}${timePart}${serial}`
}

const requestNumber = async (targetCode?: string, targetName?: string) => {
    const params: Record<string, string> = {}
    if (targetCode) params.targetCode = targetCode
    if (targetName) params.targetName = targetName
    try {
        const res = await myaxios.get('/api/Number/GenerateNumber', { params })
        if (res?.data?.code === 200 && res?.data?.data) {
            return String(res.data.data)
        }
        throw new Error(res?.data?.message || '生成编号失败')
    } catch (err) {
        const ruleRes = await myaxios.get('/api/Number/QueryNumberingRules', { params })
        const list = Array.isArray(ruleRes?.data?.data) ? ruleRes.data.data : []
        if (list.length > 0) {
            return buildCodeFromRule(list[0])
        }
        throw new Error('未找到对应的编号规则，请先配置编号规则')
    }
}

const SALES_ORDER_RULE_CANDIDATES = [
    { targetCode: 'SalesOrder', targetName: '销售单号' },
    { targetCode: 'SalesOrder', targetName: '销售订单' },
    { targetCode: 'SalesOrderNo', targetName: '销售单号' },
    { targetCode: 'XSDH', targetName: '销售单号' },
]

const generateSalesOrderNo = async () => {
    if (generatingCode.value) return
    generatingCode.value = true
    try {
        let lastError: any = null
        for (const candidate of SALES_ORDER_RULE_CANDIDATES) {
            try {
                const code = await requestNumber(candidate.targetCode, candidate.targetName)
                if (code) {
                    salesForm.salesOrderNo = code
                    ElMessage.success('编号生成成功')
                    return
                }
            } catch (error) {
                lastError = error
            }
        }
        throw lastError || new Error('未找到可用的编号规则，请先配置编号规则')
    } catch (error: any) {
        ElMessage.error(error?.message || '生成编号失败')
    } finally {
        generatingCode.value = false
    }
}

const handleCustomerChange = (value: string | number) => {
    const target = customerOptions.value.find((item) => String(item.customerId) === String(value))
    if (target) {
        salesForm.customerName = target.customerName
        salesForm.salesContact = target.linkMan || salesForm.salesContact
        salesForm.salesContactPhone = target.linkPhone || salesForm.salesContactPhone
    } else {
        salesForm.customerName = ''
    }
}

const loadCustomers = async () => {
    try {
        const res = await myaxios.get('/api/Customer/GetCustomer', {
            params: {
                pageindex: 1,
                pagesize: 1000,
            },
        })
        if (res.data.code === 200) {
            customerOptions.value = res.data.data?.data || []
        }
    } catch (error) {
        console.error('获取客户失败:', error)
    }
}

const normalizeOrganizationNodes = (list: any[]): OrganizationItem[] => {
    const normalized: OrganizationItem[] = []
    const traverse = (items: any[]) => {
        items.forEach((item) => {
            const node: OrganizationItem = {
                organizationId: String(item.organizationId ?? item.id ?? item.value ?? ''),
                organizationName: item.organizationName ?? item.label ?? item.name ?? '',
                organizationParentId: (() => {
                    const pid =
                        item.organizationParentId ??
                        item.parentId ??
                        item.pid ??
                        item.parent ??
                        null
                    return pid === null || pid === undefined || pid === '' ? null : String(pid)
                })(),
                children: [],
            }
            normalized.push(node)
            if (item.children && item.children.length) {
                traverse(item.children)
            }
        })
    }
    traverse(list)
    return normalized
}

const buildOrgTree = (list: OrganizationItem[]) => {
    const map = new Map<string, OrganizationItem>()
    const tree: OrganizationItem[] = []
    list.forEach((item) => {
        const id = String(item.organizationId)
        map.set(id, { ...item, organizationId: id, children: [] })
    })
    map.forEach((item) => {
        const parentId = item.organizationParentId ? String(item.organizationParentId) : ''
        if (parentId && map.has(parentId)) {
            const parent = map.get(parentId)!
            parent.children!.push(item)
        } else {
            tree.push(item)
        }
    })
    return tree
}

const loadOrganizations = async () => {
    try {
        const res = await myaxios.get('api/Supplier/GetOrganization')
        if (res.data.code === 200) {
            const normalized = normalizeOrganizationNodes(res.data.data || [])
            const tree = buildOrgTree(normalized)
            orgTreeData.value = tree.length ? tree : normalized
        }
    } catch (error) {
        console.error('获取部门失败:', error)
    }
}

const loadUsers = async () => {
    try {
        const res = await myaxios.get('api/Supplier/GetUser')
        if (res.data.code === 200) {
            userList.value = res.data.data || []
        }
    } catch (error) {
        console.error('获取人员失败:', error)
    }
}

const loadUnitOptions = async () => {
    try {
        const res = await myaxios.get('/api/Unit/GetUnitList')
        if (res.data.code === 200 || res.data.success) {
            unitOptions.value = (res.data.data || []).map((unit: any) => ({
                unitId: unit.unitId,
                unitName: unit.unitName,
            }))
        }
    } catch (error) {
        console.error('获取单位失败:', error)
    }
}

const filteredOrgTree = computed(() => {
    if (!orgSearchText.value) return orgTreeData.value
    const keyword = orgSearchText.value.toLowerCase()
    const filterTree = (nodes: OrganizationItem[]): OrganizationItem[] => {
        const result: OrganizationItem[] = []
        nodes.forEach((node) => {
            const match = node.organizationName.toLowerCase().includes(keyword)
            const children = node.children ? filterTree(node.children) : []
            if (match || children.length) {
                result.push({ ...node, children })
            }
        })
        return result
    }
    return filterTree(orgTreeData.value)
})

const filteredUserList = computed(() => {
    let list = userList.value
    if (salesForm.organizationId) {
        list = list.filter(
            (user) => user.organizationId && String(user.organizationId) === String(salesForm.organizationId),
        )
    }
    if (userSearchText.value) {
        const keyword = userSearchText.value.toLowerCase()
        list = list.filter((user) => user.userName.toLowerCase().includes(keyword))
    }
    return list
})

const openOrgDialog = () => {
    orgDialogVisible.value = true
}

const handleSelectOrg = (node: OrganizationItem) => {
    selectedOrgNode.value = node
}

const confirmOrg = () => {
    if (!selectedOrgNode.value) {
        ElMessage.warning('请先选择部门')
        return
    }
    salesForm.organizationId = String(selectedOrgNode.value.organizationId)
    salesForm.organizationName = selectedOrgNode.value.organizationName
    clearUserSelection()
    orgDialogVisible.value = false
}

const openUserDialog = () => {
    if (!salesForm.organizationId) {
        ElMessage.warning('请先选择销售部门')
        return
    }
    userDialogVisible.value = true
}

const handleSelectUser = (row: UserItem) => {
    selectedUser.value = row
}

const confirmUser = () => {
    if (!selectedUser.value) {
        ElMessage.warning('请先选择人员')
        return
    }
    salesForm.userId = String(selectedUser.value.userId)
    salesForm.userName = selectedUser.value.userName
    userDialogVisible.value = false
}

const clearOrgSelection = () => {
    salesForm.organizationId = ''
    salesForm.organizationName = ''
    selectedOrgNode.value = null
    clearUserSelection()
}

const clearUserSelection = () => {
    salesForm.userId = ''
    salesForm.userName = ''
    selectedUser.value = null
}

const handleDetailSelectionChange = (rows: SalesDetailItem[]) => {
    selectedDetailRows.value = rows
}

const removeDetail = (index: number) => {
    salesDetails.value.splice(index, 1)
}

const removeSelectedDetails = () => {
    if (!selectedDetailRows.value.length) {
        ElMessage.warning('请选择需要移除的明细行')
        return
    }
    salesDetails.value = salesDetails.value.filter((item) => !selectedDetailRows.value.includes(item))
    selectedDetailRows.value = []
    ElMessage.success('已移除选中的明细')
}

const updateDetailAmount = (row: SalesDetailItem) => {
    const qty = typeof row.quantity === 'number' ? row.quantity : Number(row.quantity || 0)
    const price = typeof row.unitPrice === 'number' ? row.unitPrice : Number(row.unitPrice || 0)
    row.quantity = qty > 0 ? qty : 0
    row.unitPrice = price >= 0 ? price : 0
    row.amount = Number((row.quantity * row.unitPrice).toFixed(2))
}

const handleSpecificationChange = (row: SalesDetailItem) => {
    row.unitName = row.specificationModel || row.unitName
}

const totalProductKinds = computed(() => salesDetails.value.length)
const totalProductQuantity = computed(() =>
    salesDetails.value.reduce((sum, item) => sum + (item.quantity || 0), 0),
)
const totalProductAmount = computed(() =>
    salesDetails.value.reduce((sum, item) => sum + (item.amount || 0), 0),
)

const openProductDialog = () => {
    productDialogVisible.value = true
    selectedProducts.value = []
    if (!productList.value.length) {
        searchProducts()
    }
}

const buildUnitGroupsFromProduct = (product: ProductListItem): UnitOptionGroup[] => {
    const groups: UnitOptionGroup[] = []
    const mainUnits: UnitOption[] = []
    const assistUnits: UnitOption[] = []

    const normalizeUnit = (val: any) => {
        if (!val) return ''
        if (typeof val === 'string') return val
        if (typeof val === 'object') return val.unitName || val.unit || val.label || ''
        return String(val)
    }

    const mainUnit = normalizeUnit(
        product.productUnit || product.mainUnit || product.unitDisplay || product.mainUnitName,
    )
    if (mainUnit) {
        mainUnits.push({ label: mainUnit, value: mainUnit, description: '主单位' })
    }

    const rawAssist =
        product.auxiliaryUnits ||
        product.assistUnits ||
        product.unitOptions ||
        product.unitList ||
        product.units ||
        []

    const assistList = Array.isArray(rawAssist) ? rawAssist : [rawAssist]
    assistList.forEach((item) => {
        const label = normalizeUnit(item)
        if (!label) return
        assistUnits.push({ label, value: label, description: '辅助单位' })
    })

    if (mainUnits.length) groups.push({ label: '主单位', options: mainUnits })
    if (assistUnits.length) groups.push({ label: '辅助单位', options: assistUnits })
    return groups.length ? groups : [{ label: '主单位', options: [{ label: mainUnit || '主单位', value: mainUnit || '' }] }]
}

const normalizeProductRecord = (record: any): ProductListItem | null => {
    const productId =
        record.productId ??
        record.productID ??
        record.id ??
        record.ProductId ??
        record.productid ??
        null
    if (!productId) return null
    const specification = record.productUnit ?? record.unitDisplay ?? record.mainUnit ?? ''
    const unit = record.productSpecification ?? record.productspecification ?? record.specification ?? ''
    return {
        ...record,
        productId,
        productName: record.productName ?? record.name ?? '',
        productCode: record.productCode ?? record.code ?? '',
        producttypeName: record.producttypeName ?? record.productTypeName,
        productUnit: specification,
        unitDisplay: specification,
        productSpecification: unit,
        specification: unit,
        productspecification: unit,
        inventoryCurrtnumber: record.inventoryCurrtnumber ?? record.currentInventory ?? 0,
        productOutMoney: record.productOutMoney ?? record.salesPrice ?? record.productInmoney ?? 0,
    }
}

const buildProductKey = (item: ProductListItem) =>
    `${item.productId}_${item.productCode}_${item.productSpecification || ''}`

const normalizeProductList = (list: any[]): ProductListItem[] => {
    const map = new Map<string, ProductListItem>()
    list.forEach((item) => {
        const normalized = normalizeProductRecord(item)
        if (!normalized) return
        const key = buildProductKey(normalized)
        if (!map.has(key)) {
            map.set(key, normalized)
        }
    })
    return Array.from(map.values())
}

const enrichProductUnits = (list: ProductListItem[]) => {
    const dynamicUnits = new Set<string>()
    list.forEach((item) => {
        if (item.productUnit) dynamicUnits.add(item.productUnit)
        if (item.productSpecification) dynamicUnits.add(item.productSpecification)
    })
    const ordered: string[] = [...DEFAULT_UNIT_OPTIONS]
    dynamicUnits.forEach((unit) => {
        if (unit && !ordered.includes(unit)) ordered.push(unit)
    })
    productUnitOptions.value = ordered
}

const searchProducts = async () => {
    productTableLoading.value = true
    try {
        const res = await myaxios.get('/api/Product/GetProduct', {
            params: {
                Pageindex: productPagination.pageindex,
                PageSize: productPagination.pagesize,
                ProductName: productSearchForm.keyword,
                ProductUnit: productSearchForm.unit,
            },
        })
        if (res.data.code === 200) {
            const rawList = res.data.data?.data || []
            const normalized = normalizeProductList(rawList)
            productList.value = normalized
            productPagination.total = res.data.data?.listCount || 0
            enrichProductUnits(productList.value)
        } else {
            ElMessage.error(res.data.message || '获取货品失败')
        }
    } catch (error) {
        console.error('获取货品失败:', error)
        ElMessage.error('获取货品失败')
    } finally {
        productTableLoading.value = false
    }
}

const resetProductSearch = () => {
    productSearchForm.keyword = ''
    productSearchForm.unit = ''
    productPagination.pageindex = 1
    searchProducts()
}

const handleProductSelectionChange = (rows: ProductListItem[]) => {
    selectedProducts.value = rows
}

const handleProductSizeChange = (size: number) => {
    productPagination.pagesize = size
    productPagination.pageindex = 1
    searchProducts()
}

const handleProductCurrentChange = (page: number) => {
    productPagination.pageindex = page
    searchProducts()
}

const transformProductToDetail = (product: ProductListItem): SalesDetailItem => {
    const unitGroups = buildUnitGroupsFromProduct(product)
    const spec = product.productUnit || product.unitDisplay || ''
    const unit = product.productSpecification || product.specification || ''
    const defaultSpec = spec || unitGroups[0]?.options[0]?.value || unit || ''
    const basePrice = resolveProductPrice(product)
    return {
        lineId: `${product.productId}-${Date.now()}`,
        productId: product.productId,
        productName: product.productName,
        productCode: product.productCode,
        specificationModel: defaultSpec,
        unitName: unit || unitGroups[0]?.options[0]?.value || '',
        unitGroups,
        productTypeName: product.producttypeName,
        currentStock: product.inventoryCurrtnumber || 0,
        quantity: null,
        unitPrice: basePrice,
        amount: 0,
        remark: '',
    }
}

const confirmProductSelection = () => {
    if (!selectedProducts.value.length) {
        ElMessage.warning('请选择需要添加的货品')
        return
    }
    let added = 0
    let skipped = 0
    selectedProducts.value.forEach((item) => {
        if (salesDetails.value.find((detail) => detail.productId === item.productId)) {
            skipped++
            return
        }
        salesDetails.value.push(transformProductToDetail(item))
        added++
    })
    if (added) {
        ElMessage.success(`成功添加 ${added} 条货品`)
    }
    if (skipped) {
        ElMessage.warning(`有 ${skipped} 条重复货品已跳过`)
    }
    productDialogVisible.value = false
    selectedProducts.value = []
}

const resetForm = () => {
    salesForm.salesOrderNo = ''
    salesForm.salesOrderDate = ''
    salesForm.customerId = ''
    salesForm.customerName = ''
    salesForm.salesContact = ''
    salesForm.salesContactPhone = ''
    salesForm.organizationId = ''
    salesForm.organizationName = ''
    salesForm.userId = ''
    salesForm.userName = ''
    salesForm.reviewerName = currentLoginUser.value
    salesForm.remark = ''
    salesDetails.value = []
}

const goBack = () => {
    router.push('/GetSalesOrder')
}

const gotoCreateCustomer = () => {
    router.push('/CreateCustomer')
}

const getUnitIdByName = (name?: string | number | null) => {
    if (!name && name !== 0) return null
    const normalized = String(name)
    const hit = unitOptions.value.find((unit) => unit.unitName === normalized || String(unit.unitId) === normalized)
    if (hit) return Number(hit.unitId)
    return null
}

const buildDetailPayload = () => {
    return salesDetails.value.map((item, index) => {
        const specificationValue =
            item.specificationModel ||
            item.unitName ||
            ''
        const unitValue = item.unitName || ''
        const unitIdValue = getUnitIdByName(unitValue ?? item.unitId ?? null)
        const quantity = Number(item.quantity ?? 0)
        const price = Number(item.unitPrice ?? 0)
        const amount = Number(item.amount ?? 0)
        return {
            lineNo: index + 1,
            productId: Number(item.productId),
            productCode: String(item.productCode || ''),
            productName: String(item.productName || ''),
            specificationModel: String(specificationValue),
            unitName: unitIdValue,
            unitDisplayName: String(unitValue),
            productTypeName: String(item.productTypeName || ''),
            currentInventory: Number(item.currentStock ?? 0),
            quantity,
            salesQuantity: quantity,
            salesPrice: price,
            amount,
            salesAmount: amount,
            remark: String(item.remark || ''),
        }
    })
}

const handleSave = async () => {
    if (!salesFormRef.value) return
    if (!salesForm.salesOrderNo) {
        await generateSalesOrderNo()
        if (!salesForm.salesOrderNo) {
            ElMessage.warning('请先生成销售单号')
            return
        }
    }
    const valid = await salesFormRef.value.validate().catch(() => false)
    if (!valid) return
    if (!salesDetails.value.length) {
        ElMessage.warning('请至少添加一条销售明细')
        return
    }
    await nextTick()
    salesDetails.value.forEach(updateDetailAmount)
    const detailPayload = buildDetailPayload()
    const payload = {
        salesOrderNo: salesForm.salesOrderNo,
        salesOrderDate: salesForm.salesOrderDate
            ? new Date(salesForm.salesOrderDate).toISOString()
            : new Date().toISOString(),
        customerId: salesForm.customerId,
        customerName: salesForm.customerName,
        salesContact: salesForm.salesContact,
        salesContactPhone: salesForm.salesContactPhone,
        organizationId: salesForm.organizationId,
        organizationName: salesForm.organizationName,
        userId: salesForm.userId,
        userName: salesForm.userName,
        SalesOrderDepartment: salesForm.organizationName,
        SalesOrderUser: salesForm.userName,
        reviewerName: salesForm.reviewerName || currentLoginUser.value,
        createor: salesForm.reviewerName || currentLoginUser.value,
        createrTime: new Date().toISOString(),
        remark: salesForm.remark,
        goodsDetails: detailPayload,
        salesDetails: detailPayload,
        SalesDetails: detailPayload,
        salesOrderDetails: detailPayload,
        SalesOrderDetails: detailPayload,
        detailList: detailPayload,
        Details: detailPayload,
        totalQuantity: totalProductQuantity.value,
        totalAmount: totalProductAmount.value,
    }
    saving.value = true
    try {
        const res = await myaxios.post('/api/SalesOrder/CreateSalesOrder', payload)
        if (res.data.code === 200) {
            ElMessage.success(res.data.message || '保存成功')
            router.push('/GetSalesOrder')
        } else {
            ElMessage.error(res.data.message || '保存失败')
        }
    } catch (error) {
        console.error('保存销售订单失败:', error)
        ElMessage.error('保存失败，请稍后重试')
    } finally {
        saving.value = false
    }
}

onMounted(async () => {
    await Promise.allSettled([loadCustomers(), loadOrganizations(), loadUsers(), loadUnitOptions()])
})
</script>

<style scoped>
.sales-create-page {
    min-height: 100vh;
    background: #f5f7fb;
    padding-bottom: 80px;
}

.page-body {
    padding-bottom: 120px;
}

.sales-form {
    max-width: 1200px;
    margin: 0 auto;
}

.card-block {
    margin-bottom: 20px;
}

.card-title {
    font-weight: 600;
    font-size: 16px;
}

.detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.detail-actions {
    display: flex;
    gap: 8px;
}

.inline-input {
    display: flex;
    align-items: center;
    gap: 8px;
}

.link-btn {
    padding: 0;
}

.readonly-input :deep(.el-input__inner) {
    background: #f5f7fa;
}

.detail-summary {
    display: flex;
    gap: 24px;
    padding: 12px 0;
    font-weight: 500;
    color: #333;
}

.fixed-footer {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background: #fff;
    border-top: 1px solid #e5e7ed;
    padding: 12px 32px;
    box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.04);
}

.footer-content {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    max-width: 1200px;
    margin: 0 auto;
}

.dialog-search {
    margin-bottom: 12px;
}

.product-search-form {
    margin-bottom: 12px;
}

.product-pagination {
    margin: 16px 0 0;
    text-align: right;
}
</style>

